<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\RoomUser;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 获取用户个人信息
     */
    public function profile(Request $request)
    {
        $user = $request->user;
        
        return response()->json([
            'code' => 200,
            'data' => [
                'user_id' => $user->id,
                'nickname' => $user->nickname,
                'avatar' => $user->avatar,
                'total_score' => $user->total_score,
                'win_count' => $user->win_count,
                'lose_count' => $user->lose_count,
                'win_rate' => $user->getWinRate(),
                'last_login_time' => $user->last_login_time
            ]
        ]);
    }
    
    /**
     * 更新用户个人信息
     */
    public function updateProfile(Request $request)
    {
        $user = $request->user;
        
        $this->validate($request, [
            'nickname' => 'max:50',
            'avatar' => 'max:255'
        ]);
        
        // 更新用户信息
        if ($request->has('nickname')) {
            $user->nickname = $request->input('nickname');
        }
        
        if ($request->has('avatar')) {
            $user->avatar = $request->input('avatar');
        }
        
        $user->save();
        
        return response()->json([
            'code' => 200,
            'data' => [
                'user_id' => $user->id,
                'nickname' => $user->nickname,
                'avatar' => $user->avatar
            ],
            'message' => '个人信息更新成功'
        ]);
    }
    
    /**
     * 获取用户排名
     */
    public function getRankings(Request $request)
    {
        $user = $request->user;
        
        // 获取排名类型
        $type = $request->input('type', 'score'); // score, win_rate
        
        // 查询排名
        if ($type == 'win_rate') {
            // 胜率排名（只统计至少有10场记录的用户）
            $users = User::whereRaw('win_count + lose_count >= 10')
                ->orderByRaw('win_count / (win_count + lose_count) DESC')
                ->take(50)
                ->get();
        } else {
            // 积分排名
            $users = User::orderBy('total_score', 'desc')
                ->take(50)
                ->get();
        }
        
        // 格式化排名数据
        $rankings = [];
        $userRank = 0;
        
        foreach ($users as $index => $rankUser) {
            $rank = $index + 1;
            
            $rankingData = [
                'rank' => $rank,
                'user_id' => $rankUser->id,
                'nickname' => $rankUser->nickname,
                'avatar' => $rankUser->avatar,
                'total_score' => $rankUser->total_score,
                'win_count' => $rankUser->win_count,
                'lose_count' => $rankUser->lose_count,
                'win_rate' => $rankUser->getWinRate(),
                'is_self' => $rankUser->id == $user->id
            ];
            
            $rankings[] = $rankingData;
            
            if ($rankUser->id == $user->id) {
                $userRank = $rank;
            }
        }
        
        // 如果用户不在前50名，查询用户的排名
        if ($userRank == 0) {
            if ($type == 'win_rate') {
                $userRank = User::whereRaw('win_count + lose_count >= 10')
                    ->whereRaw('(win_count / (win_count + lose_count)) > (? / (? + ?))', [
                        $user->win_count, $user->win_count, $user->lose_count
                    ])
                    ->count() + 1;
            } else {
                $userRank = User::where('total_score', '>', $user->total_score)->count() + 1;
            }
            
            // 添加用户自己的排名信息
            $rankings[] = [
                'rank' => $userRank,
                'user_id' => $user->id,
                'nickname' => $user->nickname,
                'avatar' => $user->avatar,
                'total_score' => $user->total_score,
                'win_count' => $user->win_count,
                'lose_count' => $user->lose_count,
                'win_rate' => $user->getWinRate(),
                'is_self' => true
            ];
        }
        
        return response()->json([
            'code' => 200,
            'data' => [
                'rankings' => $rankings,
                'self_rank' => $userRank
            ]
        ]);
    }
}